﻿using Microsoft.AspNetCore.SignalR;

namespace SignalR.Server.Hubs
{
    public class ClienthHub : Hub
    {
        private readonly ILogger<ClienthHub> _logger;

        public ClienthHub(ILogger<ClienthHub> logger)
        {
            _logger = logger;
        }
        // 客户端调用服务端的方法
        public async Task SendMessage(string user, string message)
        {
            _logger.LogInformation("收到客户端发来的消息=====" +user + message);

            await Clients.Caller.SendAsync("ReceiveMessage", $"SendMessage by {user} {message} {Context.ConnectionId}"); //谁调的 返回去调谁


            //// 服务端主动调用客户端的方法
            //await Clients.All.SendMessage(user, "服务端主动调用客户端的方法");
        }
        // 给调用方法的那个人发消息
        public async Task SendMessageCaller(string message)
        {
            _logger.LogInformation("给调用方法的那个人发消息=====" + message);

            await Clients.Caller.SendAsync("给调用方法的那个人发消息");
        }

        /// <summary>
        /// 客户端连接服务端
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            var id = Context.ConnectionId;
            _logger.LogInformation($"客户端ConnectionId=>【{id}】已连接服务器！");
            return base.OnConnectedAsync();
        }
        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var id = Context.ConnectionId;
            _logger.LogInformation($"客户端ConnectionId=>【{id}】已断开服务器连接！");
            return base.OnDisconnectedAsync(exception);
        }
        //// 常用方法
        //// 给所有人发送消息
        //await Clients.All.SendAsync("ReceiveMessage", data);
        //// 给组里所有人发消息
        //await Clients.Group("Users").SendAsync("ReceiveMsg", data);
        //// 给调用方法的那个人发消息
        //await Clients.Caller.SendAsync("ReceiveMessage", data);
        //// 给除了调用方法的以外所有人发消息
        //await Clients.Others.SendAsync("ReceiveMessage", data);
        //// 给指定connectionId的人发消息
        //await Clients.User(connectionId).SendAsync("ReceiveMessage", data);
        //// 给指定connectionId的人发消息
        //await Clients.Client(connectionId).SendAsync("ReceiveMessage", data);
        //// 给指定connectionId的人发消息，同时指定多个connectionId
        //await Clients.Clients(IReadOnlyList<> connectionIds).SendAsync("ReceiveMessage", data);

        public void RunFirstStep(string msg)
        {
            _logger.LogInformation($"RunFirstStep==========={msg}");
        }
    }
}
